package com.xyz.keshe.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xyz.keshe.db.DatabaseHelper;
import com.xyz.keshe.model.Admin;

import java.util.ArrayList;
import java.util.List;

public class AdminDao {
    private final DatabaseHelper dbHelper;

    public AdminDao(Context context) {
        this.dbHelper = new DatabaseHelper(context);
    }

    // 添加管理员
    public long addAdmin(Admin admin) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_ADMIN_USERNAME, admin.getUsername());
        values.put(DatabaseHelper.COLUMN_ADMIN_PASSWORD, admin.getPassword());
        values.put(DatabaseHelper.COLUMN_ADMIN_IS_SUPER, admin.isSuper() ? 1 : 0);

        long id = db.insert(DatabaseHelper.TABLE_ADMIN, null, values);
        db.close();
        return id;
    }

    // 插入管理员（别名方法）
    public long insertAdmin(Admin admin) {
        return addAdmin(admin);
    }

    // 更新管理员
    public int updateAdmin(Admin admin) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_ADMIN_USERNAME, admin.getUsername());
        values.put(DatabaseHelper.COLUMN_ADMIN_PASSWORD, admin.getPassword());
        values.put(DatabaseHelper.COLUMN_ADMIN_IS_SUPER, admin.isSuper() ? 1 : 0);
        values.put(DatabaseHelper.COLUMN_UPDATE_TIME, "CURRENT_TIMESTAMP");

        int rowsAffected = db.update(
                DatabaseHelper.TABLE_ADMIN,
                values,
                DatabaseHelper.COLUMN_ID + " = ?",
                new String[]{String.valueOf(admin.getId())}
        );
        db.close();
        return rowsAffected;
    }

    // 删除管理员
    public int deleteAdmin(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int rowsAffected = db.delete(
                DatabaseHelper.TABLE_ADMIN,
                DatabaseHelper.COLUMN_ID + " = ?",
                new String[]{String.valueOf(id)}
        );
        db.close();
        return rowsAffected;
    }

    // 获取所有管理员
    public List<Admin> getAllAdmins() {
        List<Admin> adminList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE_ADMIN;

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Admin admin = new Admin();
                admin.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID)));
                admin.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_USERNAME)));
                admin.setPassword(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_PASSWORD)));
                admin.setSuper(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_IS_SUPER)) == 1);
                admin.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CREATE_TIME)));
                admin.setUpdateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_UPDATE_TIME)));

                adminList.add(admin);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return adminList;
    }

    // 通过ID获取管理员
    public Admin getAdminById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(
                DatabaseHelper.TABLE_ADMIN,
                null,
                DatabaseHelper.COLUMN_ID + " = ?",
                new String[]{String.valueOf(id)},
                null, null, null
        );

        Admin admin = null;
        if (cursor != null && cursor.moveToFirst()) {
            admin = new Admin();
            admin.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID)));
            admin.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_USERNAME)));
            admin.setPassword(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_PASSWORD)));
            admin.setSuper(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_IS_SUPER)) == 1);
            admin.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CREATE_TIME)));
            admin.setUpdateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_UPDATE_TIME)));
            cursor.close();
        }
        db.close();
        return admin;
    }

    // 通过用户名获取管理员
    public Admin getAdminByUsername(String username) {
        //获取一个可读的数据库实例（只读模式），用于执行查询操作。
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(
                DatabaseHelper.TABLE_ADMIN,
                null,
                DatabaseHelper.COLUMN_ADMIN_USERNAME + " = ?",
                new String[]{username},
                null, null, null
        );

        Admin admin = null;
        if (cursor != null && cursor.moveToFirst()) {
            admin = new Admin();
            admin.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID)));
            admin.setUsername(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_USERNAME)));
            admin.setPassword(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_PASSWORD)));
            admin.setSuper(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ADMIN_IS_SUPER)) == 1);
            admin.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CREATE_TIME)));
            admin.setUpdateTime(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_UPDATE_TIME)));
            cursor.close();
        }
        db.close();
        return admin;
    }

    // 验证管理员登录
    public Admin login(String username, String password) {
        Admin admin = getAdminByUsername(username);
        if (admin != null && admin.getPassword().equals(password)) {
            return admin;
        }
        return null;
    }

    // 通过用户名删除管理员
    public int deleteAdminByUsername(String username) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int rowsAffected = db.delete(
                DatabaseHelper.TABLE_ADMIN,
                DatabaseHelper.COLUMN_ADMIN_USERNAME + " = ?",
                new String[]{username}
        );
        db.close();
        return rowsAffected;
    }

    // 将所有非admin用户设置为普通管理员
    public int removeAllSuperAdminExceptDefault() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_ADMIN_IS_SUPER, 0);
        
        int rowsAffected = db.update(
                DatabaseHelper.TABLE_ADMIN,
                values,
                DatabaseHelper.COLUMN_ADMIN_USERNAME + " != ?",
                new String[]{"admin"}
        );
        db.close();
        return rowsAffected;
    }
} 